package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.ListNode;
import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

import java.util.HashMap;
import java.util.Map;

class MaximumWidthOfBinaryTree {
    // 2022-08-15 09:56:32
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        Map<Integer, Integer> left = new HashMap<>();
        int ans = 0;

        public int widthOfBinaryTree(TreeNode root) {
            dfs(root, 0, 0);
            return ans;
        }

        private void dfs(TreeNode root, int depth, int pos) {
            if (root == null) return;
            // 最左端，不能覆盖
            left.computeIfAbsent(depth, x->pos);
            ans = Math.max(ans, pos - left.get(depth) + 1);
            dfs(root.left, depth + 1, pos * 2);
            dfs(root.right, depth + 1, pos * 2 + 1);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}